#include "toast.h"

#include <QScreen>
#include <QApplication>
#include <QVBoxLayout>
#include <QLabel>
#include <QTimer>
#include <QPainter>
#include <QPainterPath>

Toast::Toast(const QString &text)
{
    // 1. 设置窗口的基本参数
    this->setFixedSize(300,50);
    this->setWindowFlags(Qt::FramelessWindowHint);
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setAttribute(Qt::WA_TranslucentBackground);
    this->setStyleSheet("QDialog { background-color:rgb(255,255,255)}");

    // 2. 先考虑一下窗口的位置
    // 获取整个屏幕的尺寸，通过primaryScreen();
    QScreen* screen = QApplication::primaryScreen();
    int width = screen->size().width();
    int height = screen->size().height();
    int x = (width - this->width()) / 2;
    int y = height - this->height() - 400;
    this->move(x,y);

    // 3. 添加水平布局管理器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0,0,0,0);
    this->setLayout(vlayout);

    // 4. 创建显示文本的Label
    QLabel* label = new QLabel();
    label->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    label->setAlignment(Qt::AlignCenter);
    label->setStyleSheet("QLabel { font-size: 25px}");
    label->setText(text);
    vlayout->addWidget(label);

    // 5. 实现2s后消失
    QTimer* timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,[=](){
        timer->stop();
        // 核心代码，关闭当前窗口
        this->close();
    });
    timer->start(1000);

}

void Toast::showMessage(const QString &text)
{
    Toast* toast = new Toast(text);
    toast->show();
}

void Toast::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);  // 抗锯齿

    // 3. 绘制圆角矩形背景
    QPainterPath path;
    path.addRoundedRect(rect(), 15, 15);  // 圆角半径
    painter.fillPath(path, QColor("#B0B0B0"));
}
